<template>
  <div class="container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="110px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" style="width: 60%"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="creatorName">
        <el-input v-model="ruleForm.creatorName" style="width: 30%"></el-input>
      </el-form-item>
      <el-form-item label="封面" prop="coverImg">
        <div
          v-on:click="uploadCover()"
          v-if="ruleForm.coverImg && ruleForm.coverImg.length == 0"
        >
          <img
            src="./../../assets/image/7.png"
            style="width: 250px; cursor: pointer"
            alt=""
          />
        </div>
        <elUploadImages
          v-if="ruleForm.coverImg && ruleForm.coverImg.length > 0"
          :isMultiple="false"
          :limit="1"
          :imageList="ruleForm.coverImg"
          @callbackImg="uploadImage"
        />
        <div ref="cutBox" style="visibility: hidden; ">
          <ImgCutter @cutDown="cutDown" :cancel="cancelCut" :cutWidth="600" :cutHeight="500" :moveAble="false" :confirm="cancelCut" rate="16:9"  ref="imageCutter">
            <el-button slot="cancel" v-on:click="cancelCut()">取消</el-button>
            <el-button slot="confirm" type="primary" style="margin-left:10px" v-on:click="cancelCut()">确定</el-button>
          </ImgCutter>
        </div>
      </el-form-item>
      <el-form-item label="请选择类型" prop="categoryId">
        <el-select
          v-model="ruleForm.categoryId"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否审批" prop="isCheck">
          <el-radio-group v-model="ruleForm.isCheck">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      <el-form-item label="新闻正文" prop="content">
        <!-- <div id="editor44" ref="editor44"></div> -->

        <div>
          <my-tinymce :id="'Content'" v-model="ruleForm.content"></my-tinymce>
          <!-- <quillEditor
            @input="getInput"
            :coverImg="ruleForm.coverImg"
            v-model="ruleForm.content"
          ></quillEditor> -->
        </div>
      </el-form-item>
      <!-- <el-form-item label="原文链接" prop="links">
                <el-input v-model="ruleForm.links" style="width: 60%;"></el-input>
            </el-form-item> -->
      <!-- <el-form-item label="是否置顶" prop="isTop">
                <el-radio-group v-model="ruleForm.isTop">
                    <el-radio :label="0">否</el-radio>
                    </el-radio>
                    <el-radio :label="1">是</el-radio>
                </el-radio-group>
            </el-form-item> -->

      <el-form-item>
        <el-button @click="resetForm('ruleForm')">保存为草稿</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// import E from "wangeditor";
import ImgCutter from "vue-img-cutter";
import myTinymce from "@/components/tinymce.vue";
import elUploadImages from "@/components/elUploadImages"; //图片上传
import quillEditor from "@/components/quillEditor"; //图片上传
import {
  findPage,
  addNews,
  newsFindById,
  newsEdit,
  findCategoryData,
} from "../../api/index";
export default {
  name: "news",
  components: {elUploadImages, quillEditor, myTinymce, ImgCutter },
  data() {
    let validatePass2 = (rule, value, callback) => {
      if (value && !this.$publicJS.URL.test(value)) {
        callback(new Error("请输入正确的网址格式"));
      } else {
        callback();
      }
    };
    return {
      options: [],

      query: {
        offset: 1,
        limit: 99,
      },
      ruleForm: {
        title: "", //新闻标题
        creatorName: "", //作者
        content: "", //正文
        coverImg: [], //封面
        categoryId: "", //分类
        // links: '',
        isCheck: 0,//是否需要审批
        categoryName: "", //分类名称
      },
      rules: {
        // links: [
        //     { required:  false, message: "请输入原文链接", trigger: "change" },
        //     { validator: validatePass2, trigger: "change" }],
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 75,
            message: "长度在 3 到 75 个字符",
            trigger: "blur",
          },
        ],
        creatorName: [
          { required: false, message: "请输入作者", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        coverImg: [
          { required: true, message: "请上传封面", trigger: "change" },
        ],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
        content: [{ required: true, message: "请输入正文", trigger: "change" }],
        isTop: [
          { required: true, message: "请选择是否置顶", trigger: "change" },
        ],
      },
      editor: null,
    };
  },
  created() {
    this.getData();
  },
  async mounted() {
    let t = this;
    if (this.$route.query.isNew == "edit") {
      await this.newsDetail();
    }
  },
  methods: {
    cancelCut(){
      // this.$refs.imageCutter.visible = false;
      this.$refs.cutBox.style.visibility = "hidden";
    },
    uploadCover() {
      // visibility: visible
      this.$refs.cutBox.style.visibility = "visible";
      this.$nextTick(() => {
        this.$refs.imageCutter.handleOpen();
        this.$refs.imageCutter.visible = true;
      });
      this.$forceUpdate();
      console.log(this.$refs.imageCutter);
    },
    cutDown(event) {
      console.log(event);
      let form = new FormData();
      form.append("file", event.file);
      this.$http
        .post(
          "http://139.215.190.237:8081/api/management/addNews/uploadImg",
          form
        )
        .then((res) => {
          this.ruleForm.coverImg = [res.data.data];
         this.cancelCut()
        },error=>{
          this.$message.error('上传失败')
          this.cancelCut()        });
    },
    async newsDetail() {
      let res = await newsFindById({ id: this.$route.query.id });
      console.log(
        "%c [ res ]-110",
        "font-size:13px; background:pink; color:#bf2c9f;",
        res
      );
      if (res.data.status == 100) {
        res.data.data.coverImg = res.data.data.coverImg
          ? [res.data.data.coverImg]
          : [];
        this.ruleForm.title = res.data.data.title;
        this.ruleForm.creatorName = res.data.data.creatorName;
        this.ruleForm.content = res.data.data.content;
        this.ruleForm.coverImg = res.data.data.coverImg;
        this.ruleForm.categoryId = res.data.data.categoryId;
        this.ruleForm.categoryName = res.data.data.categoryName;
        this.ruleForm.isCheck = res.data.data.isCheck;
        this.ruleForm.id = res.data.data.id;
      }
    },
    async getData() {
      let res = await findCategoryData();
      if (res.data.status == 100) {
        this.options = res.data.data.map((res) => {
          return {
            value: res.id,
            label: res.name,
          };
        });
      }
    },
    getInput(value) {
      this.ruleForm.content = value;
    },
    async onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {});
    },
    //封面图
    uploadImage(value) {
      console.log(value, "上传封面图片的结果1111");
      this.ruleForm.coverImg = value;
    },
    async submitForm() {
      if (
        this.ruleForm.content == "" ||
        this.ruleForm.content == null ||
        this.ruleForm.content == "<div>&nbsp;</div>"
      ) {
        this.$message.error("请输入自定义内容");
        return;
      }
      this.ruleForm.coverImg =
        this.ruleForm.coverImg && this.ruleForm.coverImg.length > 0
          ? this.ruleForm.coverImg.toString()
          : "";
      this.options.map((res) => {
        if (this.ruleForm.categoryId == res.value) {
          this.ruleForm.categoryName = res.label;
        }
      });

      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.$route.query.isNew == "new") {
            let res = await addNews(this.ruleForm);
            if (res.data.status == 100) {
              this.$router.push({ path: "/newsEstablish" });
            }
          } else {
            let res = await newsEdit(this.ruleForm);
            if (res.data.status == 100) {
              this.$router.push({ path: "/newsEstablish" });
            }
          }
        } else {
          console.log("error submit!!");
          this.ruleForm.coverImg = this.ruleForm.coverImg
            ? [this.ruleForm.coverImg]
            : [];
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style scoped>
.search {
  display: flex;
  flex-flow: wrap;
  margin-bottom: 2rem;
  /* visibility: visible; */
}

.tables {
  margin: 0 1rem;
}
</style>
